<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>兑换记录管理 - MeetUp 管理后台</title>

    {% load static %}
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --sidebar-width: 250px;
            --header-height: 60px;
            --primary-color: #FF8C42;
            --secondary-color: #FFB347;
            --accent-color: #FFD166;
            --light-color: #f8f9fa;
            --dark-color: #2D3047;
            --text-color: #333333;
            --bg-color: #FFF9F2;
        }

        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            overflow: hidden;
            background-color: white;
        }

        .stat-card {
            text-align: center;
            padding: 25px 15px;
            position: relative;
        }

        .stat-card i {
            font-size: 2.5rem;
            margin-bottom: 15px;
            color: var(--primary-color);
            background: rgba(255, 140, 66, 0.1);
            width: 70px;
            height: 70px;
            line-height: 70px;
            border-radius: 50%;
            display: inline-block;
        }

        .stat-card .number {
            font-size: 2.2rem;
            font-weight: bold;
            color: var(--dark-color);
            margin: 10px 0;
        }

        .badge-pending { background-color: #ffc107; color: #212529; }
        .badge-shipped { background-color: #17a2b8; }
        .badge-completed { background-color: #28a745; }
        .badge-cancelled { background-color: #dc3545; }

        .action-buttons .btn {
            margin: 2px;
        }
    </style>
</head>
<body>
    <!-- 侧边栏和顶部导航栏 -->
    <!-- 这里省略重复的侧边栏和导航栏代码 -->

    <div id="content">
        <nav class="navbar navbar-expand navbar-light bg-white">
            <div class="container-fluid">
                <button type="button" id="sidebarCollapse" class="btn btn-primary">
                    <i class="bi bi-list"></i>
                </button>
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> {{ request.user.username }}
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/user/person_center/"><i class="bi bi-person"></i> 个人资料</a></li>
                            <li><a class="dropdown-item" href="#"><i class="bi bi-gear"></i> 设置</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/user/logout/"><i class="bi bi-box-arrow-right"></i> 退出</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="container-fluid p-4">
            <h2 class="mb-4">兑换记录管理</h2>

            <!-- 统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-arrow-left-right"></i>
                        <div class="number">{{ exchange_stats.total }}</div>
                        <div class="label">总兑换数</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-clock"></i>
                        <div class="number">{{ exchange_stats.pending }}</div>
                        <div class="label">待处理</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-check-circle"></i>
                        <div class="number">{{ exchange_stats.completed }}</div>
                        <div class="label">已完成</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-x-circle"></i>
                        <div class="number">{{ exchange_stats.cancelled }}</div>
                        <div class="label">已取消</div>
                    </div>
                </div>
            </div>

            <!-- 筛选栏 -->
            <div class="card">
                <div class="card-body">
                    <form class="row g-3" method="get">
                        <div class="col-md-4">
                            <select class="form-select" name="status">
                                <option value="">所有状态</option>
                                {% for status_value, status_name in status_choices %}
                                    <option value="{{ status_value }}" {% if status_filter == status_value %}selected{% endif %}>
                                        {{ status_name }}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-4">
                            <select class="form-select" name="product_id">
                                <option value="">所有商品</option>
                                {% for product in products %}
                                    <option value="{{ product.id }}" {% if product_id == product.id|stringformat:"i" %}selected{% endif %}>
                                        {{ product.name }}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-4">
                            <button type="submit" class="btn btn-primary w-100">筛选</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 兑换记录列表 -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">兑换记录</h5>
                    <span class="text-muted">共 {{ page_obj.paginator.count }} 条记录</span>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>用户</th>
                                    <th>商品信息</th>
                                    <th>使用积分</th>
                                    <th>状态</th>
                                    <th>收货信息</th>
                                    <th>兑换码</th>
                                    <th>兑换时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for exchange in page_obj %}
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            {% if exchange.user.avatar %}
                                                <img src="{{ exchange.user.avatar.url }}" alt="{{ exchange.user.username }}" style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover; margin-right: 10px;">
                                            {% else %}
                                                <div style="width: 32px; height: 32px; background: #f8f9fa; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 10px;">
                                                    <i class="bi bi-person text-muted"></i>
                                                </div>
                                            {% endif %}
                                            <div>
                                                <strong>{{ exchange.user.username }}</strong>
                                                <br>
                                                <small class="text-muted">{{ exchange.user.email }}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            {% if exchange.product.image %}
                                                <img src="{{ exchange.product.image.url }}" alt="{{ exchange.product.name }}" style="width: 40px; height: 40px; object-fit: cover; border-radius: 8px; margin-right: 10px;">
                                            {% else %}
                                                <div style="width: 40px; height: 40px; background: #f8f9fa; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-right: 10px;">
                                                    <i class="bi bi-box text-muted"></i>
                                                </div>
                                            {% endif %}
                                            <div>
                                                <strong>{{ exchange.product.name }}</strong>
                                                <br>
                                                <small class="text-muted">{{ exchange.product.get_category_display }}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="fw-bold text-warning">{{ exchange.points_used }}</span> 积分
                                    </td>
                                    <td>
                                        <span class="badge badge-{{ exchange.status }}">
                                            {{ exchange.get_status_display }}
                                        </span>
                                        {% if exchange.tracking_number %}
                                            <br>
                                            <small class="text-muted">快递: {{ exchange.tracking_number }}</small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if exchange.product.category == 'physical' %}
                                            {% if exchange.shipping_address %}
                                                <strong>{{ exchange.contact_name }}</strong>
                                                <br>
                                                <small>{{ exchange.contact_phone }}</small>
                                                <br>
                                                <small class="text-muted">{{ exchange.shipping_address|truncatechars:30 }}</small>
                                            {% else %}
                                                <span class="text-muted">未填写</span>
                                            {% endif %}
                                        {% else %}
                                            <span class="text-muted">虚拟商品</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if exchange.exchange_code %}
                                            <code>{{ exchange.exchange_code }}</code>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ exchange.created_at|date:"Y-m-d H:i" }}</td>
                                    <td>
                                        <div class="action-buttons">
                                            {% if exchange.status == 'pending' %}
                                                <button type="button" class="btn btn-success btn-sm update-status-btn"
                                                        data-exchange-id="{{ exchange.id }}"
                                                        data-new-status="shipped"
                                                        data-exchange-product="{{ exchange.product.name }}"
                                                        data-exchange-user="{{ exchange.user.username }}">
                                                    <i class="bi bi-truck"></i> 发货
                                                </button>
                                                <button type="button" class="btn btn-primary btn-sm update-status-btn"
                                                        data-exchange-id="{{ exchange.id }}"
                                                        data-new-status="completed"
                                                        data-exchange-product="{{ exchange.product.name }}"
                                                        data-exchange-user="{{ exchange.user.username }}">
                                                    <i class="bi bi-check-lg"></i> 完成
                                                </button>
                                                <button type="button" class="btn btn-danger btn-sm update-status-btn"
                                                        data-exchange-id="{{ exchange.id }}"
                                                        data-new-status="cancelled"
                                                        data-exchange-product="{{ exchange.product.name }}"
                                                        data-exchange-user="{{ exchange.user.username }}">
                                                    <i class="bi bi-x-lg"></i> 取消
                                                </button>
                                            {% elif exchange.status == 'shipped' %}
                                                <button type="button" class="btn btn-success btn-sm update-status-btn"
                                                        data-exchange-id="{{ exchange.id }}"
                                                        data-new-status="completed"
                                                        data-exchange-product="{{ exchange.product.name }}"
                                                        data-exchange-user="{{ exchange.user.username }}">
                                                    <i class="bi bi-check-lg"></i> 完成
                                                </button>
                                            {% endif %}

                                            {% if exchange.status == 'shipped' and not exchange.tracking_number %}
                                                <button type="button" class="btn btn-info btn-sm add-tracking-btn"
                                                        data-exchange-id="{{ exchange.id }}"
                                                        data-exchange-product="{{ exchange.product.name }}">
                                                    <i class="bi bi-upc-scan"></i> 添单号
                                                </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="8" class="text-center py-4">
                                        <i class="bi bi-arrow-left-right display-4 text-muted"></i>
                                        <p class="mt-2 text-muted">暂无兑换记录</p>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    {% if page_obj.has_other_pages %}
                    <nav>
                        <ul class="pagination justify-content-center">
                            {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if status_filter %}&status={{ status_filter }}{% endif %}{% if product_id %}&product_id={{ product_id }}{% endif %}">上一页</a>
                            </li>
                            {% endif %}

                            {% for i in page_obj.paginator.page_range %}
                            <li class="page-item {% if page_obj.number == i %}active{% endif %}">
                                <a class="page-link" href="?page={{ i }}{% if status_filter %}&status={{ status_filter }}{% endif %}{% if product_id %}&product_id={{ product_id }}{% endif %}">{{ i }}</a>
                            </li>
                            {% endfor %}

                            {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if status_filter %}&status={{ status_filter }}{% endif %}{% if product_id %}&product_id={{ product_id }}{% endif %}">下一页</a>
                            </li>
                            {% endif %}
                        </ul>
                    </nav>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 更新状态模态框 -->
    <div class="modal fade" id="updateStatusModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">更新兑换状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确定要将 <strong id="exchangeUser"></strong> 兑换的 <strong id="exchangeProduct"></strong> 标记为 <strong id="newStatusDisplay"></strong> 吗？</p>
                    <div id="trackingNumberSection" class="mb-3 d-none">
                        <label for="trackingNumber" class="form-label">快递单号</label>
                        <input type="text" class="form-control" id="trackingNumber" placeholder="请输入快递单号">
                    </div>
                    <input type="hidden" id="exchangeId">
                    <input type="hidden" id="newStatus">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmUpdateStatusBtn">确认更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加快递单号模态框 -->
    <div class="modal fade" id="addTrackingModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加快递单号</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>为 <strong id="trackingProductName"></strong> 添加快递单号：</p>
                    <div class="mb-3">
                        <label for="newTrackingNumber" class="form-label">快递单号</label>
                        <input type="text" class="form-control" id="newTrackingNumber" placeholder="请输入快递单号">
                    </div>
                    <input type="hidden" id="trackingExchangeId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmAddTrackingBtn">确认添加</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 更新状态按钮
            document.addEventListener('click', function(e) {
                if (e.target.closest('.update-status-btn')) {
                    const button = e.target.closest('.update-status-btn');
                    const exchangeId = button.dataset.exchangeId;
                    const newStatus = button.dataset.newStatus;
                    const productName = button.dataset.exchangeProduct;
                    const userName = button.dataset.exchangeUser;

                    const statusMap = {
                        'shipped': '已发货',
                        'completed': '已完成',
                        'cancelled': '已取消'
                    };

                    document.getElementById('exchangeId').value = exchangeId;
                    document.getElementById('newStatus').value = newStatus;
                    document.getElementById('exchangeUser').textContent = userName;
                    document.getElementById('exchangeProduct').textContent = productName;
                    document.getElementById('newStatusDisplay').textContent = statusMap[newStatus];

                    // 显示或隐藏快递单号输入框
                    const trackingSection = document.getElementById('trackingNumberSection');
                    if (newStatus === 'shipped') {
                        trackingSection.classList.remove('d-none');
                    } else {
                        trackingSection.classList.add('d-none');
                    }

                    const modal = new bootstrap.Modal(document.getElementById('updateStatusModal'));
                    modal.show();
                }

                // 添加快递单号按钮
                if (e.target.closest('.add-tracking-btn')) {
                    const button = e.target.closest('.add-tracking-btn');
                    const exchangeId = button.dataset.exchangeId;
                    const productName = button.dataset.exchangeProduct;

                    document.getElementById('trackingExchangeId').value = exchangeId;
                    document.getElementById('trackingProductName').textContent = productName;

                    const modal = new bootstrap.Modal(document.getElementById('addTrackingModal'));
                    modal.show();
                }
            });

            // 确认更新状态
            document.getElementById('confirmUpdateStatusBtn').addEventListener('click', function() {
                const exchangeId = document.getElementById('exchangeId').value;
                const newStatus = document.getElementById('newStatus').value;
                const trackingNumber = document.getElementById('trackingNumber').value;

                updateExchangeStatus(exchangeId, newStatus, trackingNumber);
            });

            // 确认添加快递单号
            document.getElementById('confirmAddTrackingBtn').addEventListener('click', function() {
                const exchangeId = document.getElementById('trackingExchangeId').value;
                const trackingNumber = document.getElementById('newTrackingNumber').value.trim();

                if (!trackingNumber) {
                    alert('请输入快递单号');
                    return;
                }

                updateExchangeStatus(exchangeId, 'shipped', trackingNumber);
            });
        });

        function updateExchangeStatus(exchangeId, status, trackingNumber = '') {
            const formData = new FormData();
            formData.append('status', status);
            if (trackingNumber) {
                formData.append('tracking_number', trackingNumber);
            }

            fetch(`/user/admin/points/exchange/${exchangeId}/update/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    // 关闭所有打开的模态框
                    const modals = document.querySelectorAll('.modal');
                    modals.forEach(modal => {
                        const modalInstance = bootstrap.Modal.getInstance(modal);
                        if (modalInstance) {
                            modalInstance.hide();
                        }
                    });
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败: ' + error.message);
            });
        }

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</body>
</html>